package com.simblog.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.simblog.common.utils.TokenUtil;

public class TokenInterceptor extends HandlerInterceptorAdapter{

	public static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
	
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String token = request.getParameter("token");
		
		if(StringUtils.isBlank(token)){
			logger.error("用户token没有传");
			response.sendRedirect(request.getContextPath() + "/p/error/token_null_error.jhtml");
			return false;
		}
		
		if(!TokenUtil.isExpired(token)){
			logger.error("用户token已过期");
			response.sendRedirect(request.getContextPath() + "/p/error/token_expired_error.jhtml");
			return false;
		}
		
		return super.preHandle(request, response, handler);
	}
	
}
